package service

import (
	"context"
	coreV1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

func GetPVCList(clientSet *kubernetes.Clientset, namespaceName string) (pvcList *coreV1.PersistentVolumeClaimList, err error) {
	pvcList, err = clientSet.CoreV1().PersistentVolumeClaims(namespaceName).List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	return pvcList, err
}

func GetPVC(clientSet *kubernetes.Clientset, namespaceName string, PVCName string) (pvcInfo *coreV1.PersistentVolumeClaim, err error) {
	pvcInfo, err = clientSet.CoreV1().PersistentVolumeClaims(namespaceName).Get(context.TODO(), PVCName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return pvcInfo, err
}

func CreatePVC(clientSet *kubernetes.Clientset, request CreatePVCRequest) (pvcInfo *coreV1.PersistentVolumeClaim, err error) {

	pvcSrc := new(coreV1.PersistentVolumeClaim)
	pvcSrc.ObjectMeta.Name = request.PvcName
	pvcSrc.Spec.AccessModes = request.AccessModes

	//设置存储大小
	var resourceQuantity resource.Quantity
	resourceQuantity.Set(request.StorageSize * 1000 * 1000 * 1000)
	pvcSrc.Spec.Resources.Requests = coreV1.ResourceList{
		"storage": resourceQuantity,
	}

	//使用存储卷名字
	if len(request.StorageClassName) != 0 {
		pvcSrc.Spec.StorageClassName = &request.StorageClassName
	}

	//创建pvc
	pvcInfo, err = clientSet.CoreV1().PersistentVolumeClaims(request.NamespaceName).Create(context.TODO(), pvcSrc, metaV1.CreateOptions{})
	if err != nil {
		return nil, err
	}
	return pvcInfo, err
}

func DeletePvc(clientSet *kubernetes.Clientset, request DeletePVCRequest) (err error) {
	err = clientSet.CoreV1().PersistentVolumeClaims(request.NamespaceName).Delete(context.TODO(), request.PvcName, metaV1.DeleteOptions{})
	if err != nil {
		return err
	}
	return nil
}
